﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Components.TextBoxValidator
{
    public partial class TextBoxValidator : UserControl
    {
        [DefaultValue(true)]
        public bool IgnoreEmptyText
        {
            get;
            set;
        }

        public string RegularExpression
        {
            get;
            set;
        }

        public string ErrorMessage
        {
            get;
            set;
        }

        public string Mask
        {
            get { return textBox1.Mask; }
            set { textBox1.Mask = value; }
        }

        public TextBoxValidator()
        {
            InitializeComponent();
            this.IgnoreEmptyText = true;
            this.textBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
        }

        private void textBox1_Validated(object sender, EventArgs e)
        {
            if (IgnoreEmptyText && string.IsNullOrEmpty(this.textBox1.Text))
                return;
            Regex regex = new Regex(this.RegularExpression);
            if (!regex.IsMatch(textBox1.Text))
                errorProvider1.SetError(this, ErrorMessage);
            else
                errorProvider1.SetError(this, "");
        }
    }
}
